<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
        <!-- 提醒区 -->
        <el-alert
            :closable="false"
            title="注意：只允许为第三级分类设置相关参数！"
            type="warning"
            show-icon>
        </el-alert>
        <!-- 级联选择器 选择商品分类 -->
        <el-row class="selectCate">
                <span>选择商品分类：</span>
                <el-cascader
                    clearable
                    v-model="selectKeys"
                    :options="parentCateList"
                    :props="cascaderProps"
                    @change="parentCateChange">
                </el-cascader>
        </el-row>
        <!-- 标签页区 -->
        <el-tabs v-model="paramsActiveName" @tab-click="paramsHandleClick">
            <!-- 添加动态参数面板 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button size="mini" type="primary" :disabled="isBtnDis" @click="addManyParamsdialogVisible = true">添加参数</el-button>
                <!-- 动态参数表格 -->
                <el-table border stripe :data="manyParamsData">
                    <el-table-column type="expand">
                      <template slot-scope="scope">
                        <!-- <el-row v-for="(item,index) in scope.row.attr_vals" :key='index'>
                          <el-col>{{item}}</el-col>
                        </el-row> -->
                        <el-tag
                          :key="index"
                          v-for="(item,index) in scope.row.attr_vals"
                          closable
                          :disable-transitions="false"
                          @close="handleClose(i,scope.row)">
                          {{item}}
                        </el-tag>
                        <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                    + New Tag</el-button>

                      </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <!-- {{scope.row.attr_id}} -->
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParamsdialog(scope.row)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <!-- 添加静态属性面板 -->
            <el-tab-pane label="静态属性" name="only">
                <el-button size="mini" type="primary" :disabled="isBtnDis" @click="addManyParamsdialogVisible = true">添加属性</el-button>
                <!-- 静态属性表格 -->
                <el-table border stripe :data="onlyParamsData">
                    <el-table-column type="expand">
                      <template slot-scope="scope">
                        <!-- <el-row v-for="(item,index) in scope.row.attr_vals" :key='index'>
                          <el-col>{{item}}</el-col>
                        </el-row> -->
                        <el-tag
                          :key="index"
                          v-for="(item,index) in scope.row.attr_vals"
                          closable
                          :disable-transitions="false"
                          @close="handleClose(i,scope.row)">
                          {{item}}
                        </el-tag>
                        <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                    + New Tag</el-button>

                      </template>
                    </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <!-- {{scope.row.attr_id}} -->
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParamsdialog(scope.row)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>

    <!-- 添加动态参数对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addManyParamsdialogVisible"
      width="50%" @close="addManyParamsdialogClose">
        <el-form :model="addManyForm" :rules="ManyFormRules" ref="addManyFormRef" label-width="80px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addManyForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addManyParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addManyParams()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamsdialogVisible"
      width="50%" @close="editParamsdialogClose">
        <el-form :model="editForm" :rules="ManyFormRules" ref="editFormRef" label-width="80px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'params',
  data () {
    return {
      parentCateList: [],
      // 级联选择器双向绑定数据
      selectKeys: [],
      // 指定级联选择器配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 标签页双向绑定值
      paramsActiveName: 'many',
      // 动态参数表格数据
      manyParamsData: [],
      // 静态属性表格数据
      onlyParamsData: [],
      // 添加动态参数表单数据
      addManyForm: {
        attr_name: ''
      },
      // 控制添加动态参数对话框显示与隐藏
      addManyParamsdialogVisible: false,
      ManyFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '参数名称长度在2-10个字符之间', trigger: 'blur' }
        ]
      },
      // 修改 数据
      editForm: {},
      editParamsdialogVisible: false
    }
  },
  created () {
    this.getParentCateList()
  },
  methods: {
    // 获取父级分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error('获取父级分类列表失败')
      this.parentCateList = res.data
    //   console.log(this.parentCateList)
    },
    // 监听级联选择器改变事件
    parentCateChange () {
      this.getGoodsParamsList()
    },
    // 监听标签页点击事件
    paramsHandleClick () {
      this.getGoodsParamsList()
    },
    // 获取商品参数
    async getGoodsParamsList () {
      // 如果选中的不是3级分类
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.manyParamsData = []
        this.onlyParamsData = []
        return false
      } else {
      // 证明选中的是三级分类
      //   console.log(this.selectKeys)
      //   console.log(this.paramsActiveName)
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.paramsActiveName } })
        if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          item.inputVisible = false
          item.inputValue = ''
        })

        console.log(res.data)

        if (this.paramsActiveName === 'many') {
          this.manyParamsData = res.data
        } else {
          this.onlyParamsData = res.data
        }
      }
    },
    // 监听动态参数对话框关闭事件
    addManyParamsdialogClose () {
      this.$refs.addManyFormRef.resetFields()
    },
    // 添加动态参数
    addManyParams () {
      this.$refs.addManyFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addManyForm.attr_name,
          attr_sel: this.paramsActiveName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addManyParamsdialogVisible = false
        this.getGoodsParamsList()
      })
    },
    // 展示修改对话框
    async showEditParamsdialog (row) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        params: { attr_sel: this.paramsActiveName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      this.editForm = res.data
      this.editParamsdialogVisible = true
    },
    // 监听 修改对话框 关闭
    editParamsdialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.paramsActiveName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        this.editParamsdialogVisible = false
        this.getGoodsParamsList()
      })
    },
    // 删除参数
    async removeParams (attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除参数成功')
      this.getGoodsParamsList()
    },
    // 监听 attr_vals 文本框事件
    async handleInputConfirm (row) {
      // console.log(row.inputValue)
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 显示文本框
    showInput (row) {
      row.inputVisible = true
      // $nextTick方法的作用 就是当页面上的元素被重新渲染后才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 关闭文本框
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 保存 attr_vals
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.paramsActiveName,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改参数项成功')
    }
  },
  computed: {
    // 标签页按钮是否禁用
    isBtnDis () {
      if (this.selectKeys.length === 3) {
        return false
      } else {
        return true
      }
    },
    // 当前选中的三级分类id
    cateId () {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[this.selectKeys.length - 1]
      } else {
        return null
      }
    },
    // 添加动态参数|静态属性
    titleText () {
      if (this.paramsActiveName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
    .selectCate{
        margin-top: 15px;
    }
    .el-tabs{
        margin-top: 15px;
    }
    .el-tag{
      margin: 5px;
    }
    .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: center;
    }
</style>
